import pygame
import sys
from settings import Settings
from spirit import Snake, Wall, Home, Bomb
import time
import easygui as g

# 测试enterbox
# mg = g.enterbox('请输入你的名字', title='新纪录') # 文本输入框
# print(mg)

# 全局常量
UP = 1          # w
LEFT = 2        # a
DOWN = 3        # s
RIGHT = 4       # d

score = 0       # 分数
hp = 4          # 大本营生命值

enter = True

pygame.init()
# 通过设置对象获取设置
st_obj = Settings()

is_running = False
first_game = True

# 设置窗口大小
# width = 1920
# height = 1080
width = st_obj.screen_width
height = st_obj.screen_height

# 边界厚度，单位是格子，始终保持(蛇的长度 // 10) + 1
tick = 1

# 追加分数测试数据
# with open('sources.txt', 'a', encoding='utf-8') as sources:
#     sources.write('硅基憨憨 '+ str(500) + ' ' + '\n')
#     sources.close()
# 分数列表变量
scores = []
# 读取从文本文档读取分数
top_f = open('top.txt', 'r', encoding='utf-8-sig')
top_str = top_f.readlines()
for s in top_str:
    scores.append(s.split(' ')[:2])


# print(scores)
# 排序，取前五名
scores = sorted(scores, key=lambda x:x[1])[::-1]
# print(scores)

if len(scores) > 5:
    scores = scores[:5]




# print(sources_str)
# print(sources_str.split(' '))


# _wall = (10, height - 10, 10, width - 10)
# 创建窗口， 宽加长一部分，显示分数和血量
screen = pygame.display.set_mode((width+200, height))
pygame.display.set_caption("贪吃蛇-保卫基地")      # 窗口标题

# 设置背景颜色
bg_color = st_obj.bg_color

# 网格线颜色
line_color = st_obj.line_color

# 初始化蛇对象
snake = Snake()
wall = Wall(20)
home = Home()
bomb = Bomb((0, 0, 0), snake, tick)
while True:
    # 重绘屏幕
    screen.fill(bg_color)
    snake.draw(screen)
    wall.draw(screen)
    # 遮挡右侧多出的墙
    pygame.draw.rect(screen, bg_color, (width, 0, 100, 400), 0)
    home.draw(screen)
    bomb.draw(screen)
    for friend in snake.friends:
        friend.draw(screen)
        friend.move()
    if snake.eat_bomb(bomb):
        bomb = Bomb((0, 0, 0), snake, tick)
        score += 10
    tick = len(snake._nodes) // 10 +1
    wall.tick = tick*20
    for i in range(1, height // 20):
        pygame.draw.line(screen, line_color, (0, 20 * i), (width, 20 * i))

    # 画竖线
    for i in range(1, width // 20):
        pygame.draw.line(screen, line_color, (20 * i, 0), (20 * i, height))

    # 监听事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            key = event.key
            if key in (pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d,
                       pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT, pygame.K_UP):
                if key == pygame.K_w or key == pygame.K_UP:
                    new_dir = UP
                if key == pygame.K_a or key == pygame.K_LEFT:
                    new_dir = LEFT
                if key == pygame.K_s or key == pygame.K_DOWN:
                    new_dir = DOWN
                if key == pygame.K_d or key == pygame.K_RIGHT:
                    new_dir = RIGHT
                snake.change_dir(new_dir)
            elif key == pygame.K_SPACE:
                if is_running:
                    snake.shoot()
                else:
                    first_game = False
                    is_running = True
            elif key == pygame.K_r:
                # 重新初始化, 待封装
                snake = Snake()
                hp = 4
                score = 0
                tick = 1
                wall = Wall(20)
                home = Home()
                bomb = Bomb((0, 0, 0), snake, tick)
                is_running = True
                enter = True
                # 分数列表变量
                scores = []
                # 读取从文本文档读取分数
                top_f = open('top.txt', 'r', encoding='utf-8-sig')
                top_str = top_f.readlines()
                for s in top_str:
                    scores.append(s.split(' ')[:2])

                # 排序，取前五名
                scores = sorted(scores, key=lambda x: x[1])[::-1]
                print(scores)

                if len(scores) > 5:
                    scores = scores[:5]

    if is_running:
        # print('running')
        if snake._aline and hp > 0:
            snake.move()
            bomb.move()
        else:
            is_running = False
            # 结算分数
            if len(scores) < 5 or score > int(scores[len(scores)-1][1]):
                print(scores[len(scores)-1][1])
                # 窗口输入用户名
                # 文本文档中追加
                if enter:
                    mg = g.enterbox('请输入你的名字', title='新纪录')  # 文本输入框
                    while mg == None:
                        mg = g.enterbox('请输入你的名字', title='新纪录')  # 文本输入框
                    nickname = mg
                    with  open('top.txt', 'a') as f:
                        f.write(nickname + ' ' + str(score) + ' ' + '\n')
                        f.close()
                        enter = False

    elif first_game:
        textFont = pygame.font.Font("C:\Windows\Fonts\STCAIYUN.TTF", 30)
        textSurface = textFont.render("空格开始游戏", True, (233, 50, 50))
        screen.blit(textSurface, (350, 300))

    else:
        textFont = pygame.font.Font("C:\Windows\Fonts\STCAIYUN.TTF", 30)
        textSurface = textFont.render("R重新开始游戏", True, (233, 50, 50))
        screen.blit(textSurface, (350, 300))
        first_game = False
    if not snake._aline or hp <= 0:
        # 显示游戏结束
        textFont = pygame.font.Font("C:\Windows\Fonts\STCAIYUN.TTF", 30)
        textSurface = textFont.render("游戏结束", True, (233, 50, 50))
        screen.blit(textSurface, (350, 250))
    # 分数与血量
    textFont = pygame.font.Font("C:\Windows\Fonts\simkai.ttf", 20)
    scoreSurface = textFont.render("分数:"+str(score), True, (50, 50, 50))
    screen.blit(scoreSurface, (width+10, 50))
    hpSurface = textFont.render("血量:"+str(hp), True, (50, 50, 50))
    screen.blit(hpSurface, (width + 10, 150))
    # 排行榜，最高分，可以在循环外绘制, 不可以，每次会清空屏幕
    pSurface = textFont.render("排行榜:", True, (50, 50, 50))
    screen.blit(pSurface, (width + 10, 200))
    top_y = 230
    for s in scores:
        topSurface = textFont.render(s[0] + ' ' + s[1], True, (50, 50, 50))
        screen.blit(topSurface, (width + 10, top_y))
        top_y += 30

    # 判断
    # 判断敌对炸弹
    bomb_state = bomb.manage_bomb(bomb,tick)
    # 如果敌对炸弹遇到大本营
    if bomb_state == 3:
        hp -= 1
        bomb = Bomb((0, 0, 0), snake, tick)
    # 依次判断friend的状态
    for friend in snake.friends:
        friend_state = friend.manage_bomb(bomb, tick)
        # 如果超出范围， 从列表中删除
        if friend_state == 1:
            snake.friends.remove(friend)
        # 如果遇到炸弹
        if friend_state == 2:
            snake.friends.remove(friend)
            bomb = Bomb((0, 0, 0), snake, tick)
            score += 20
    snake.out_wall(tick)
    snake.eat_self()
    # 刷新屏幕
    pygame.display.flip()

    time.sleep(0.3)

# 优化空间
# 绘制的顺序
# 初始化的方法封装
# 文字位置，大小等参数可以提取出来

